package com.cl.park.util;
import org.hibernate.HibernateException;
import org.hibernate.Session;

import session.HibernateSessionFactory;
/**
 * @author 沈宁
 */
public class HibernateUtil {
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	private static org.hibernate.SessionFactory sessionFactory;

	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(org.hibernate.SessionFactory sessionFactory) {
		HibernateUtil.sessionFactory = sessionFactory;
	}

	private static org.springframework.orm.hibernate3.HibernateTemplate ht = new org.springframework.orm.hibernate3.HibernateTemplate();

	static {
		try {
			sessionFactory = ht.getSessionFactory();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/***
	 * 获得session
	 * 
	 * @return
	 * @throws HibernateException
	 */
	public static Session getSession() throws HibernateException {
		Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}

		return session;
	}

	public static void rebuildSessionFactory() {
		try {
			sessionFactory = ht.getSessionFactory();
		} catch (Exception e) {
			System.err.println("无法 �?baseDao �?创建 SessionFactory ");
			e.printStackTrace();
		}
	}
}